'use client';

import { useEffect, useState } from "react";
import {
  Table,
  message,
  Button,
  Modal,
  Form,
  Input,
  Pagination,
  Checkbox,
  Spin,
} from "antd";
import { useUser } from "../../context/userContext";
import api from "../../utils/api";
import styles from '@/components/Font.module.css';

export default function AlertManagementPage() {
  const { user } = useUser();
  const accessToken = user?.access_token || "";

  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalAlerts, setTotalAlerts] = useState(0);
  const [Alerts, setAlerts] = useState([]);
  const [createAlertModalVisible, setCreateAlertModalVisible] = useState(false);
  const [postAlertModalVisible, setPostAlertModalVisible] = useState(false);
  const [selectedAlert, setSelectedAlert] = useState(null);
  const [userList, setUserList] = useState([]);
  const [selectedUserIds, setSelectedUserIds] = useState([]);
  const [loadingUsers, setLoadingUsers] = useState(false);

  const [createAlertForm] = Form.useForm();

  // 新增分页相关变量
  const [currentUserPage, setCurrentUserPage] = useState(1); // 当前用户分页
  const [userPageSize, setUserPageSize] = useState(10); // 用户分页大小
  const [totalUsers, setTotalUsers] = useState(0); // 用户总数

  // 获取提醒
  const fetchAlerts = async () => {
    try {
      const response = await api.get("/alerts", {
        headers: { Authorization: `Bearer ${accessToken}` },
        params: { page: currentPage, pageSize },
      });
      setAlerts(response.data.alerts);
      setTotalAlerts(response.data.total || 0);
    } catch (error) {
      message.error("提醒加载失败");
    }
  };

  useEffect(() => {
    fetchAlerts();
  }, [currentPage, pageSize, accessToken]);

  // 获取用户列表
  const fetchUsers = async (page = 1, limit = 10) => {
    try {
      setLoadingUsers(true);
      const response = await api.get("/users/all", {
        headers: { Authorization: `Bearer ${accessToken}` },
        params: { page, limit },
      });
      setUserList(response.data.uers || []);
      setTotalUsers(response.data.total || 0); // 更新用户总数
    } catch (error) {
      message.error("加载用户列表失败");
    } finally {
      setLoadingUsers(false);
    }
  };

  // 创建提醒
  const handleCreateAlert = async (values) => {
    try {
      const response = await api.post("/alerts", values, {
        headers: {
          Authorization: `Bearer ${accessToken}`,
          "Content-Type": "application/json",
        },
      });

      if (response.data.success) {
        message.success("创建成功");
        setCreateAlertModalVisible(false);
        await fetchAlerts();
      }
    } catch (error) {
      message.error("创建消息提醒失败");
    }
  };

  // 批量发布提醒
  const handlePostAlert = async () => {
    if (!selectedAlert) {
      return message.error("未选中提醒");
    }
    if (selectedUserIds.length === 0) {
      return message.error("请至少选择一个接收者");
    }

    try {
      const response = await api.post(
        "/alerts/recipients",
        {
          alert_id: selectedAlert.alert_id,
          receiverIds: selectedUserIds,
        },
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data.success) {
        message.success("提醒发布成功");
        setPostAlertModalVisible(false);
        setSelectedUserIds([]); // 清空选中的用户
        await fetchAlerts();
      }
    } catch (error) {
      message.error("提醒发布失败");
    }
  };

  // 删除提醒
  const handleDeleteAlert = async (alert_id) => {
    try {
      const response = await api.delete(`/alerts/delete?alert_id=${alert_id}`, {
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      if (response.data.success) {
        message.success("提醒消息删除成功");
        await fetchAlerts();
      }
    } catch (error) {
      message.error("提醒消息删除失败");
    }
  };

  const alertColumns = [
    { 
      title: "提醒ID", 
      dataIndex: "alert_id", 
      key: "alert_id",
      className: styles.text,
      width: 100,
    },
    { 
      title: "提醒信息", 
      dataIndex: "message", 
      key: "message",
      className: styles.text,
      width: 300,
    },
    { 
      title: "发起者ID", 
      dataIndex: "poster_id", 
      key: "poster_id",
      className: styles.text,
      width: 100,
    },
    {
      title: "操作",
      key: "action",
      className: styles.text,
      width: 220,
      render: (_, record) => (
        <div className="flex space-x-2">
          <Button 
            type="primary" 
            className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
            onClick={async () => {
              setSelectedAlert(record);
              setPostAlertModalVisible(true);
              await fetchUsers(1, 10); // 每次弹出时加载用户列表
            }}
          >
            批量发布提醒
          </Button>
          <Button 
            type="primary" 
            danger 
            className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
            onClick={() => handleDeleteAlert(record.alert_id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="bg-[#F4EDEB] rounded-2xl shadow-md p-6">
      <h2 className={`${styles.titlesmall} text-xl mb-6 text-[#7A6E6E]`}>提醒管理</h2>
      
      <Button 
        type="primary" 
        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-4 py-2 mb-6"
        onClick={() => setCreateAlertModalVisible(true)}
      >
        创建提醒
      </Button>
      
      {/* 表格容器 - 固定表头，内容可滚动 */}
      <div className="overflow-hidden bg-white rounded-xl shadow-sm h-[calc(100vh-260px)]">
        <Table
          columns={alertColumns}
          dataSource={Alerts}
          pagination={false}
          className="bordered={false}"
          rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-[#F4EDEB]/50'}
          size="middle"
          scroll={{ y: "calc(100vh - 260px)" }}
          components={{
            header: {
              cell: ({ className, ...restProps }) => (
                <th
                  {...restProps}
                  className={`${className} ${styles.titlesmall} text-base font-semibold text-[#7A6E6E] bg-[#F4EDEB] sticky top-0 z-10`}
                />
              ),
            },
          }}
        />
      </div>
      
      {/* 分页组件 */}
      <div className="flex justify-center mt-6">
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={totalAlerts}
          onChange={newPage => setCurrentPage(newPage)}
          className="bg-white p-3 rounded-lg shadow-sm"
        />
      </div>

      {/* 创建提醒 Modal */}
      <Modal
        title={<span className={`${styles.titlesmall} text-base font-semibold text-[#7A6E6E]`}>创建消息提醒</span>}
        visible={createAlertModalVisible}
        onOk={() => createAlertForm.submit()}
        onCancel={() => setCreateAlertModalVisible(false)}
        className="rounded-xl overflow-hidden bg-[#F4EDEB]"
        style={{ borderRadius: '16px' }}
        footer={[
          <Button 
            key="cancel" 
            className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
            onClick={() => setCreateAlertModalVisible(false)}
          >
            取消
          </Button>,
          <Button 
            key="ok" 
            type="primary"
            className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
            onClick={() => createAlertForm.submit()}
          >
            创建
          </Button>,
        ]}
      >
        <div className="p-4 bg-white rounded-lg shadow-sm">
          <Form
            form={createAlertForm}
            layout="vertical"
            onFinish={handleCreateAlert}
          >
            <Form.Item
              label={<span className={`${styles.text} font-medium text-gray-700`}>消息内容</span>}
              name="message"
              rules={[{ required: true, message: "请输入提醒消息内容" }]}
            >
              <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
            </Form.Item>
          </Form>
        </div>
      </Modal>

      {/* 批量发布提醒 Modal */}
      <Modal
        title={<span className={`${styles.titlesmall} text-base font-semibold text-[#7A6E6E]`}>选择提醒接收者</span>}
        visible={postAlertModalVisible}
        onOk={handlePostAlert}
        onCancel={() => {
          setPostAlertModalVisible(false);
          setSelectedUserIds([]); // 重置勾选的用户
        }}
        className="rounded-xl overflow-hidden bg-[#F4EDEB]"
        style={{ borderRadius: '16px' }}
        footer={[
          <Button 
            key="cancel" 
            className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
            onClick={() => {
              setPostAlertModalVisible(false);
              setSelectedUserIds([]);
            }}
          >
            取消
          </Button>,
          <Button 
            key="ok" 
            type="primary"
            className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
            onClick={handlePostAlert}
          >
            发布提醒
          </Button>,
        ]}
      >
        <div className="p-4 bg-white rounded-lg shadow-sm">
          {loadingUsers ? (
            <div className="flex justify-center py-8">
              <Spin />
            </div>
          ) : (
            <>
              <div className="mb-4 pb-2 border-b border-gray-200">
                <div className={`${styles.text} font-medium text-gray-700 mb-3`}>选择接收用户</div>
                <Checkbox.Group
                  value={selectedUserIds}
                  onChange={(checkedValues) => {
                    // 计算当前页用户的 uid 列表
                    const currentPageUserIds = userList.map((user) => user.uid);
                    // 从全局选中中移除当前页的 uid
                    const filteredOldSelections = selectedUserIds.filter(
                      (id) => !currentPageUserIds.includes(id)
                    );
                    // 把当前页新选中的 uid 加进去
                    setSelectedUserIds([
                      ...filteredOldSelections,
                      ...checkedValues,
                    ]);
                  }}
                  style={{ display: "flex", flexDirection: "column", gap: 8 }}
                >
                  {userList.map((user) => (
                    <Checkbox key={user.uid} value={user.uid}>
                      <span
                        style={{
                          textTransform: "uppercase",
                          fontSize: "16px",
                        }}
                      >
                        ID: {user.uid} --- {user.username}
                      </span>
                    </Checkbox>
                  ))}
                </Checkbox.Group>
              </div>
              
              {/* 用户分页 */}
              <div className="flex justify-center mt-4">
                <Pagination
                  current={currentUserPage}
                  pageSize={userPageSize}
                  total={totalUsers}
                  onChange={(newPage) => {
                    setCurrentUserPage(newPage);
                    fetchUsers(newPage, userPageSize); // 切换页面时重新加载用户
                  }}
                  showSizeChanger={false} // 固定分页大小
                  className="bg-[#F4EDEB] p-2 rounded-lg"
                />
              </div>
            </>
          )}
        </div>
      </Modal>
    </div>
  );
}